﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace Vortex.Tutorials {
    
    ///<summary>Launches game application based on its id</summary>
    static class Launcher {
        
        public static void Launch(string id) {
			Assembly thisAssembly = Assembly.GetExecutingAssembly();
			Type targetType = null;
			foreach (Type type in thisAssembly.GetTypes()) {
				if (type.Name.Equals(id, StringComparison.InvariantCultureIgnoreCase)) {
					targetType = type;
					break;
				}
			}

			//try to invoke target type
			if (null != targetType) {
				if (typeof(Game).IsAssignableFrom(targetType)) {
					InvokeGame((Game)Activator.CreateInstance(targetType));
				} else if (typeof(System.Windows.Forms.Form).IsAssignableFrom(targetType)) {
					RunForm((System.Windows.Forms.Form)Activator.CreateInstance(targetType));
				} else {
					Console.WriteLine("Unable to host target type " + targetType.FullName);
				}
			} else {
				Console.WriteLine("Unable to find type matching id = " + id);
			}
        }

        private static void InvokeGame (Game game) {
            using (game) {
                game.Run();
            }
        }

        private static void RunForm(System.Windows.Forms.Form form) {
#if DEBUG
            form.ShowDialog();
#else
            System.Windows.Forms.Application.Run(form);
#endif
        }
    }
}
